package com.asa.ui.H;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Scanner;

public class GameData{
	
	private int maxTurn;
	private Board starterBoard;
	private int N,M;
	
	private Board showBoard;
	
	
	public GameData(String filename) {
		
		if (filename==null) {
			throw new IllegalArgumentException("filename cannot be null");
		}
		
		Scanner scanner = null;
		
		try {
			
			File file = new File(filename);
			if (!file.exists()) {
				throw new IllegalArgumentException(filename+ " file do not exists");
			}
			FileInputStream fis = new FileInputStream(file);
			scanner = new Scanner(fis,"UTF-8");
			
			String turnline = scanner.nextLine();
			this.maxTurn = Integer.parseInt(turnline);
			
			ArrayList<String> lines = new ArrayList<>();
			while (scanner.hasNextLine()) {

				String line = scanner.nextLine();
				lines.add(line);
				
			}
			
			starterBoard = new Board(lines.toArray(new String[lines.size()]));
			N = starterBoard.getN();
			M = starterBoard.getM();
			starterBoard.print();
			starterBoard.print();
			showBoard = new Board(starterBoard);
			
			
			
			
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			if (scanner!=null) {
				scanner.close();
			}
		}
		
		
		
	}
	
	
	
	public int getN() {
		return N;
	}
	public int getM() {
		return M;
	}
	
	public boolean inArea(int x,int y) {
		return x>=0 && x<N && y>=0 && y<M;
	}



	public Board getShowBoard() {
		return showBoard;
	}
	
	
	public boolean solve() {
		
		if (maxTurn<0) {
			return false;
		}
		return solve(starterBoard,maxTurn);
		
		
	}


	private static int[][] d = {{1,0},{0,1},{0,-1}};

	private boolean solve(Board board, int turn) {
		// TODO Auto-generated method stub
		System.out.println("solve");
		if (board==null || turn <0) {
			throw new IllegalArgumentException("Illegal arguments");

		}
		if (turn==0) {
			return board.isWin();
		}
		
		if (board.isWin()) {
			return true;
		}
		
		for (int x = 0; x < N; x++) {
			for (int y = 0; y < M; y++) {
				
				if (board.getData(x, y)!=Board.EMPTY) {
					
					for (int i = 0; i < 3; i++) {
						int newX = x+d[i][0];
						int newY = y+d[i][1];
						
						
						if (inArea(newX, newY)) {
							String swapString = String.format("swap (%d,%d) and (%d,%d)", x,y,newX,newY);
							Board nextBoard = new Board(board,board,swapString);
							nextBoard.swap(x,y,newX,newY);
							nextBoard.run();
							if(solve(nextBoard,turn-1)) {
								return true;
							}
						}
						
					}
					
				}
				
			}
			
		}
		
		return false;
	}
	
	
	
}
